package com.youlu.campus.service.tencentcloud;

import com.alibaba.fastjson.JSON;
import com.tencentcloudapi.captcha.v20190722.CaptchaClient;
import com.tencentcloudapi.captcha.v20190722.models.DescribeCaptchaResultRequest;
import com.tencentcloudapi.captcha.v20190722.models.DescribeCaptchaResultResponse;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.ActivityUserRecord;
import com.youlu.campus.entity.CaGroupInfo;
import com.youlu.campus.entity.PayCategoryConfig;
import com.youlu.campus.entity.VO.req.CaCollectReq;
import com.youlu.campus.entity.VO.req.CaptchaRequest;
import com.youlu.campus.entity.VO.req.H5PayCaptchaRequest;
import com.youlu.campus.service.activity.impl.PlatformOtherActivityService;
import com.youlu.campus.service.ca.CaGroupInfoService;
import com.youlu.campus.service.ca.impl.CaCollectService;
import com.youlu.campus.service.cache.CacheActivityUserRecordService;
import com.youlu.campus.service.pay.PayCategoryConfigService;
import com.youlu.campus.service.visitor.UserInfoExtendService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class TencentCloudCaptchaService {

    /**
     *平台SECRET_ID
     */
//   private final static String  TENCENTCLOUD_SECRET_ID = "AKIDqVt1tUord9OM3TbS2LN7bokPnukJbdNq";
    /**
     *平台SECRET_KEY
     */
//    private final static String  TENCENTCLOUD_SECRET_KEY = "DAqFNEp94nGUR8ZjdGelbAUaQ0LRHrBE";
    /**
     * 平台SECRET_ID
     */
    private final static String TENCENTCLOUD_SECRET_ID = "AKIDu3cCoQ9218Mb10327DNnFyjVEujfgOC4";
    /**
     * 平台SECRET_KEY
     */
    private final static String TENCENTCLOUD_SECRET_KEY = "03FTnHk7Ro9Vp5YBpafh52uhO98224zn";

    /**
     * 验证码APPID
     */
    private final static Long CAPTCHA_APP_ID = 199561048L;

    /**
     * 验证码SECRETKEY
     */
    private final static String CAPTCHA_APP_SECRET_KEY = "Q3UaFJhDIpcUtuqrwaB6lTXg0";

    @Autowired
    private CacheActivityUserRecordService cacheActivityUserRecordService;

    @Lazy
    @Autowired
    private CaCollectService caCollectService;
    @Lazy
    @Autowired
    private PayCategoryConfigService payCategoryConfigService;
    @Lazy
    @Autowired
    private CaGroupInfoService caGroupInfoService;

    public Map<String, Object> h5PayCaptcha(H5PayCaptchaRequest req) {
        String mobile = req.getMobile();
        String randStr = req.getRandStr();
        String ticket = req.getTicket();
        log.info("用户收款查询校验 mobile:{}|ticket:{}|randstr:{}", mobile, ticket, randStr);
        CaptchaRequest captchaRequest = new CaptchaRequest();
        captchaRequest.setMobile(mobile);
        captchaRequest.setRandStr(randStr);
        captchaRequest.setTicket(ticket);
        captchaRequest.setUserIp(req.getUserIp());
        captchaRequest.setCaptchaAppId(199007776L);
        captchaRequest.setCaptchaAppSecretKey("IOv8haqGOCxh5CTAfRQA2VZeH");
        this.checkCaptcha(captchaRequest);
        ActivityUserRecord activityUserRecord = cacheActivityUserRecordService.findByActivityIdAndMobile(req.getActivityId(), mobile, req.getTaskBizType());
        if (Objects.isNull(activityUserRecord)) {
            log.error(":>>> 用户信息未导入到收款记录中:ActivityUserRecord,活动ID:{},手机号:{},类型:{}", req.getActivityId(), mobile, req.getTaskBizType());
            throw new BusinessException("报名手机号未达到获取等级或未报名");
        }
        CaCollectReq caCollectReq = new CaCollectReq();
        caCollectReq.setCurrentUser(req.getCurrentUser());
        caCollectReq.setActivityId(req.getActivityId());
        caCollectReq.setTaskBizType(req.getTaskBizType());
        caCollectReq.setMobile(req.getMobile());
        caCollectReq.setCaType(req.getCaType());
        return this.caCollectService.checkUser(caCollectReq);
    }

    public Map<String, Object> h5PayCaptchaV2(H5PayCaptchaRequest req) {
        String mobile = req.getMobile();
        String randStr = req.getRandStr();
        String ticket = req.getTicket();
        log.info("用户收款查询校验 mobile:{}|ticket:{}|randstr:{}", mobile, ticket, randStr);
        CaptchaRequest captchaRequest = new CaptchaRequest();
        captchaRequest.setMobile(mobile);
        captchaRequest.setRandStr(randStr);
        captchaRequest.setTicket(ticket);
        captchaRequest.setUserIp(req.getUserIp());
        captchaRequest.setCaptchaAppId(199007776L);
        captchaRequest.setCaptchaAppSecretKey("IOv8haqGOCxh5CTAfRQA2VZeH");
        this.checkCaptcha(captchaRequest);
//        ActivityUserRecord activityUserRecord = cacheActivityUserRecordService.findByActivityIdAndMobile(req.getActivityId(), mobile, req.getTaskBizType());
        PayCategoryConfig payCategoryConfig = payCategoryConfigService.findByCategoryId(req.getCategoryId(), req.getActivityId());
        CaGroupInfo caGroupInfo = caGroupInfoService.findOne(payCategoryConfig.getCaGroupId());
        req.setTaskBizType(caGroupInfo.getTaskBizType());
//        if (Objects.isNull(activityUserRecord)) {
//            log.error(":>>> 用户信息未导入到收款记录中:ActivityUserRecord,活动ID:{},手机号:{},类型:{}", req.getActivityId(), mobile, req.getTaskBizType());
//            throw new BusinessException("报名手机号未达到获取等级或未报名");
//        }
        CaCollectReq caCollectReq = new CaCollectReq();
        caCollectReq.setCurrentUser(req.getCurrentUser());
        caCollectReq.setActivityId(req.getActivityId());
        caCollectReq.setMobile(req.getMobile());
        caCollectReq.setCaType(req.getCaType());
        caCollectReq.setTaskBizType(req.getTaskBizType());
        caCollectReq.setCategoryId(req.getCategoryId());
        return this.caCollectService.checkUserV2(caCollectReq);
    }

    public void checkCaptcha(CaptchaRequest captchaRequest) {
        Long captchaType = captchaRequest.getCaptchaType();
        String mobile = captchaRequest.getMobile();
        String randStr = captchaRequest.getRandStr();
        String ticket = captchaRequest.getTicket();
        log.info("用户查询校验 mobile:{}|ticket:{}|randstr:{}", mobile, ticket, randStr);
        if (StringUtils.isAnyBlank(mobile, ticket, randStr)) {
            throw new BusinessException("校验参数错误");
        }
        try {
            Credential cred = new Credential(TENCENTCLOUD_SECRET_ID, TENCENTCLOUD_SECRET_KEY);
            CaptchaClient captchaClient = new CaptchaClient(cred, "ap-beijing");
            DescribeCaptchaResultRequest req = new DescribeCaptchaResultRequest();
            req.setTicket(ticket);
            req.setRandstr(randStr);
            req.setUserIp(captchaRequest.getUserIp());
            req.setCaptchaType(captchaType);
            req.setCaptchaAppId(captchaRequest.getCaptchaAppId());
            req.setAppSecretKey(captchaRequest.getCaptchaAppSecretKey());
            req.setNeedGetCaptchaTime(1L);
            DescribeCaptchaResultResponse describeCaptchaResultResponse = captchaClient.DescribeCaptchaResult(req);
            log.info("【验证码校验】返回结果用户查询 mobile:{}|result:{}", mobile, JSON.toJSONString(describeCaptchaResultResponse));
            if (1 != describeCaptchaResultResponse.getCaptchaCode()) {
                log.error("【验证码校验】error mobile:{}|captchaCode:{}|evilLevel:{}", mobile, describeCaptchaResultResponse.getCaptchaCode(), describeCaptchaResultResponse.getEvilLevel());
                throw new BusinessException("验证码错误，请重试");
            }
        } catch (TencentCloudSDKException e) {
            log.error("【验证码校验】返回结果用户查询", e);
            throw new BusinessException("验证码校验错误,请联系我们");
        } catch (BusinessException e) {
            log.error("【验证码校验】返回结果用户查询", e);
            throw e;
        } catch (Exception e) {
            log.error("【验证码校验】返回结果用户查询", e);
            throw new BusinessException("验证码校验错误,请联系我们");
        }
    }

}
